﻿using FyCacheClient.Pool;
using FySystem.Extension;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FyCacheClient
{
    /// <summary>
    /// 异步执行器
    /// </summary>
    internal class AsyncCommandExecuter
    {
        /// <summary>
        /// 异步执行指令
        /// </summary>
        /// <param name="connect"></param>
        /// <param name="data"></param>
        /// <param name="callback"></param>
        internal static void Execute(Connect connect, List<byte> data, Action<Connect, CommandResponse> callback)
        {
            try
            {
                //收到数据回调
                connect.Client.OnReceive = (simClient, frame) =>
                {
                    CommandResponse response = new CommandResponse();
                    if (frame.Frame[16] == 0x00)
                    {
                        //如果服务端没报错
                        response.Command = new byte[2];
                        response.Command[0] = data[17];
                        response.Command[1] = data[18];
                        response.Data = frame.Frame.ReadBytes(19);
                    }
                    else
                    {
                        //如果服务端报错了
                        int code = BitConverter.ToInt32(frame.Frame, 17);
                        string err = Encoding.UTF8.GetString(frame.Frame, 21, frame.Frame.Length - 21);
                        throw new Exception($"{code}#{err}");
                    }

                    callback.Invoke(connect, response);
                };

                connect.Client.Send(data);
            }
            catch (Exception)
            {
                throw;
            }
        }
    }
}
